package net.pinnoocle.playservice.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.pinnoocle.playcommon.exception.ShopException;
import net.pinnoocle.playcommon.password.PasswordUtils;
import net.pinnoocle.playcommon.response.ErrorCode;
import net.pinnoocle.playcommon.utils.BigDecimalMathUtil;
import net.pinnoocle.playcommon.utils.ConvertUtils;
import net.pinnoocle.playcommon.utils.HelpUtils;
import net.pinnoocle.playcommon.utils.JwtUtil;
import net.pinnoocle.playdao.dao.OrderDao;
import net.pinnoocle.playdao.dao.ShopDao;
import net.pinnoocle.playdao.dao.UserDao;
import net.pinnoocle.playdao.entity.*;
import net.pinnoocle.playdao.entity.admin.SaveShopParams;
import net.pinnoocle.playdao.entity.admin.ShopListSearchVo;
import net.pinnoocle.playdao.entity.admin.ShopListVo;
import net.pinnoocle.playdao.entity.admin.homepage.TopShopByGroup;
import net.pinnoocle.playdao.entity.page.PageModel;
import net.pinnoocle.playdao.entity.page.PageQuery;
import net.pinnoocle.playdao.entity.shopPc.ShopLoginParams;
import net.pinnoocle.playdao.entity.shopPc.ShopLoginResultVo;
import net.pinnoocle.playdao.entity.shopPc.homePage.DoubleVo;
import net.pinnoocle.playdao.entity.shopPc.homePage.HomePageStatisticsVo;
import net.pinnoocle.playdao.entity.shopPc.homePage.NumberVo;
import net.pinnoocle.playdao.entity.shopPc.shop.SaveShopSettingParams;
import net.pinnoocle.playdao.entity.shopPc.shop.ShopChangePassParams;
import net.pinnoocle.playdao.entity.shopPc.shop.ShopDetailVo;
import net.pinnoocle.playdao.entity.shopPc.user.UserListPageVo;
import net.pinnoocle.playdao.entity.web.group.ShopWebGroupListSearchParams;
import net.pinnoocle.playdao.entity.web.master.MasterGroupListVo;
import net.pinnoocle.playdao.entity.web.shop.*;
import net.pinnoocle.playdao.entity.web.user.homepage.ShopInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 门店表(Shop)表服务实现类
 *
 * @author ye
 * @since 2021-10-19 16:35:35
 */
@Service("shopService")
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopDao, Shop>{

    @Value("${upload.mapUrl}")
    private String uploadMapUrl;

    @Autowired
    UserServiceImpl userService;
    @Autowired
    ShopUserServiceImpl shopUserService;
    @Autowired
    UserLevelServiceImpl userLevelService;
    @Autowired
    GroupServiceImpl groupService;
    @Autowired
    MasterServiceImpl masterService;
    @Autowired
    ScriptServiceImpl scriptService;
    @Autowired
    OrderDao orderDao;
    @Autowired
    UserDao userDao;

    /**
     * 店铺列表---分页
     * @param searchVo
     * @return
     */
    public PageModel<ShopListVo> shopList(ShopListSearchVo searchVo){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(searchVo.getPage()));
        pageMap.put("pageSize",String.valueOf(searchVo.getPageSize()));

        Page<ShopListVo> page = this.baseMapper.shopList(
                new PageQuery<Shop>(pageMap).getPage(), searchVo);
        List<ShopListVo> records = page.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(page, new ArrayList<>());
        }
        return new PageModel<>(page, records);
    }

    /**
     * 添加店铺数据
     * @param saveShopParams
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveShop(SaveShopParams saveShopParams){
        try {
            Shop shop = ConvertUtils.sourceToTarget(saveShopParams, Shop.class);
            //默认密码为登录账号
            String encodePass = PasswordUtils.encode(saveShopParams.getLoginName());
            shop.setPassword(encodePass);
            shop.setCreatedTime(new Date());
            Date expireDate = DateUtil.offset(new Date(), DateField.YEAR, 1);
            shop.setExpireTime(expireDate);
            boolean result = this.save(shop);
            if(result){
                saveUserLevel(shop.getShopId());
            }
            return result;
        } catch (Exception e) {
            log.info("店铺添加失败："+e.getMessage());
            return false;
        }
    }

    /**
     * 生成默认会员等级
     * @param shopId
     * @return
     */
    private boolean saveUserLevel(String shopId){
        ArrayList<UserLevel> userLevels = new ArrayList<>();
        //钻石会员
        UserLevel userLevel = new UserLevel();
        userLevel.setShopId(shopId);
        userLevel.setLevelName("钻石会员");
        userLevel.setDiscount(0.88);
        userLevel.setAutoUpgrade(10);
        userLevel.setIconPath(uploadMapUrl+"icon_first.png");
        userLevel.setCreatedTime(new Date());
        userLevels.add(userLevel);
        //金卡会员
        UserLevel userLevel1 = new UserLevel();
        userLevel.setShopId(shopId);
        userLevel.setLevelName("金卡会员");
        userLevel.setDiscount(0.9);
        userLevel.setAutoUpgrade(5);
        userLevel.setIconPath(uploadMapUrl+"icon_second.png");
        userLevel.setCreatedTime(new Date());
        userLevels.add(userLevel);
        //银卡会员
        UserLevel userLevel2 = new UserLevel();
        userLevel.setShopId(shopId);
        userLevel.setLevelName("银卡会员");
        userLevel.setDiscount(0.95);
        userLevel.setAutoUpgrade(3);
        userLevel.setIconPath(uploadMapUrl+"icon_three.png");
        userLevel.setCreatedTime(new Date());
        userLevels.add(userLevel);
        return userLevelService.saveBatch(userLevels);
    }

    /**
     * 店铺编辑
     * @param saveShopParams
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateShop(SaveShopParams saveShopParams){
        try {
            Shop shop = ConvertUtils.sourceToTarget(saveShopParams, Shop.class);
            return this.updateById(shop);
        } catch (Exception e) {
            log.info("店铺编辑失败："+e.getMessage());
            return false;
        }
    }

    /**
     * 店铺删除
     * @param shopId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteShop(String shopId){
        try {
            return this.removeById(shopId);
        } catch (Exception e) {
            log.info("店铺删除失败："+e.getMessage());
            return false;
        }
    }

    /**
     * 店铺登录
     * @param params
     * @return
     */
    public ShopLoginResultVo shopLogin(ShopLoginParams params){
        String loginName = params.getLoginName();
        Shop shop = this.getOne(new QueryWrapper<Shop>()
                .lambda()
                .eq(Shop::getLoginName, loginName));
        if(Objects.isNull(shop)){
            throw new ShopException(ErrorCode.ACCOUNT_NOT_EXIST,"店铺不存在");
        }
        if(shop.getIsDisable() == 1){
            throw new ShopException(ErrorCode.ACCOUNT_NOT_EXIST,"店铺已被禁用");
        }
        boolean checkPwd = PasswordUtils
                .matches(shop.getPassword(), params.getTimestamp(), params.getPassWord());
        if(!checkPwd){
            throw new ShopException(ErrorCode.ACCOUNT_NOT_EXIST,"密码错误");
        }
        String token = JwtUtil.createToken(shop.getShopId(), shop.getLoginName(),shop.getShopId());
        ShopLoginResultVo loginUserVo = new ShopLoginResultVo();
        loginUserVo.setLoginName(shop.getLoginName());
        loginUserVo.setMobile(shop.getMobile());
        loginUserVo.setToken(token);
        return loginUserVo;
    }

    /**
     * 首页店铺信息
     * @param shopId
     * @return
     */
    public ShopInfoVo homePageShopInfo(String shopId){
        Shop shop = this.getById(shopId);
        if(Objects.isNull(shop)){
            return null;
        }
        return ConvertUtils.sourceToTarget(shop,ShopInfoVo.class);
    }

    /**
     * 通过授权token获取门店id
     * @return
     */
    public String getShopId(){
        String shopId = JwtUtil.getShopId();
        if(Objects.isNull(shopId) || StringUtils.isBlank(shopId)){
            throw new ShopException(ErrorCode.TOKEN_INVALID,"店铺ID获取失败，请重新登录");
        }
        return shopId;
    }

    /**
     * 店铺首页统计
     * @return
     */
    public HomePageVo shopHomePage(){
        HomePageVo homePageVo = new HomePageVo();
        String shopId = userService.getGlobalShopId();
        Shop shop = this.getById(shopId);
        homePageVo.setShopId(shopId);
        homePageVo.setShopName(shop.getShopName());
        //今日统计
        DateTime startTime = DateUtil.beginOfDay(new Date());
        DateTime endTime = DateUtil.endOfDay(new Date());
        String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
        String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");
        HashMap<String,Object> todayMap = this.baseMapper.shopStatistics(shopId, startTimeStr, endTimeStr);
        Long todayOrderNum = (Long) todayMap.get("todayOrderNum");
        double payPrice = Double.parseDouble(String.valueOf(todayMap.getOrDefault("payPrice", 0.00)));
        double appointPrice = Double.parseDouble(String.valueOf(todayMap.getOrDefault("appointPrice", 0.00)));
        double todayTurnover = BigDecimalMathUtil.add(payPrice, appointPrice);
        homePageVo.setTodayOrderNum(todayOrderNum.intValue());
        homePageVo.setTodayTurnover(todayTurnover);
        //累计统计
        HashMap<String,Object> totalMap = this.baseMapper.shopStatistics(shopId, null, null);
        Long totalOrderNum = (Long) totalMap.getOrDefault("todayOrderNum", 0);
        double totalPayPrice = Double.parseDouble(String.valueOf(totalMap.getOrDefault("payPrice", 0.00)));
        double totalAppointPrice = Double.parseDouble(String.valueOf(totalMap.getOrDefault("appointPrice", 0.00)));
        double totalTurnover = BigDecimalMathUtil.add(totalPayPrice, totalAppointPrice);
        homePageVo.setTotalOrderNum(totalOrderNum.intValue());
        homePageVo.setTotalTurnover(totalTurnover);
        //当前开局数
        int groupNum = this.baseMapper.nowGroupNum(shopId);
        homePageVo.setNowGroupNum(groupNum);
        //用户数
        int userNum = shopUserService.count(new QueryWrapper<ShopUser>()
                .lambda()
                .eq(ShopUser::getShopId, shopId));
        homePageVo.setTotalUserNum(userNum);
        //会员数
        int memberNum = shopUserService.count(new QueryWrapper<ShopUser>()
                .lambda()
                .eq(ShopUser::getShopId, shopId)
                .ne(ShopUser::getMemberLevelId,0));
        homePageVo.setTotalMemberNum(memberNum);
        return homePageVo;
    }

    /**
     * 会员列表
     * @param params
     * @return
     */
    public PageModel<UserListPageVo> userList(UserListSearchParams params){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(params.getPage()));
        pageMap.put("pageSize",String.valueOf(params.getPageSize()));

        if(params.getShopId() == null){
            String shopId = userService.getGlobalShopId();
            params.setShopId(shopId);
        }

        Page<UserListPageVo> list = this.baseMapper.userList(
                new PageQuery<ShopUser>(pageMap).getPage(),params);
        List<UserListPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        return new PageModel<>(list, records);
    }

    /**
     * 设置用户的会员级别
     * @param params
     * @return
     */
    public boolean setMemberLevelId(SetMemberLevelIdParams params){
        String userId = params.getUserId();
        try {
            ShopUser shopUser = new ShopUser();
            shopUser.setMemberLevelId(params.getMemberLevelId());
            return shopUserService.update(shopUser, new QueryWrapper<ShopUser>()
                    .lambda()
                    .eq(ShopUser::getUserId, userId));
        } catch (Exception e) {
            log.info("设置失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 店铺会员级别
     * @return
     */
    public List<SimpleUserLevelVo> userLevelList(){
        String shopId = userService.getGlobalShopId();
        List<UserLevel> list = userLevelService.list(new QueryWrapper<UserLevel>()
                .lambda()
                .eq(UserLevel::getShopId, shopId));
        return ConvertUtils.sourceToTarget(list,SimpleUserLevelVo.class);
    }

    /**
     * 用户消费记录
     * @param params
     * @return
     */
    public ExpenseDetailVo expenseDetail(ExpenseDetailSearchParams params){
        ExpenseDetailVo expenseDetailVo = new ExpenseDetailVo();
        String userId = params.getUserId();
        double totalPrice = this.baseMapper.totalExpenseAmount(userId);
        expenseDetailVo.setTotalExpenseAmount(totalPrice);
        PageModel<ExpenseDetailListPageVo> expenseDetailListPageVoPageModel = expenseDetailPage(params);
        expenseDetailVo.setExpenseDetailListPageVoPageModel(expenseDetailListPageVoPageModel);
        return expenseDetailVo;
    }

    /**
     * 某个用户的消费记录明细
     * @param params
     * @return
     */
    public PageModel<ExpenseDetailListPageVo> expenseDetailPage(ExpenseDetailSearchParams params){
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("page",String.valueOf(params.getPage()));
        pageMap.put("pageSize",String.valueOf(params.getPageSize()));

        Page<ExpenseDetailListPageVo> list = this.baseMapper.expenseDetailPage(
                new PageQuery<Order>(pageMap).getPage(),params);
        List<ExpenseDetailListPageVo> records = list.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageModel<>(list, new ArrayList<>());
        }
        return new PageModel<>(list, records);
    }

    /**
     * 门店组局管理
     * @param dateStr
     * @param groupType
     * @return
     */
    public List<MasterGroupListVo> groupList(String dateStr, Integer groupType){
        HashMap<String, String> startAndEndDate = HelpUtils.getDayStartAndEndTime(dateStr);
        String shopId = userService.getGlobalShopId();
        if(StringUtils.isBlank(shopId)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"登录失效，请重新登录");
        }
        String startDate = startAndEndDate.getOrDefault("startDate","");
        String endDate = startAndEndDate.getOrDefault("endDate","");
        ShopWebGroupListSearchParams searchParams = new ShopWebGroupListSearchParams();
        searchParams.setShopId(shopId);
        searchParams.setStartDate(startDate);
        searchParams.setEndDate(endDate);
        searchParams.setGroupType(groupType);
        List<MasterGroupListVo> masterGroupListVos = groupService.shopWebGroupList(searchParams);
        if(CollectionUtils.isEmpty(masterGroupListVos)){
            return new ArrayList<>();
        }
        for (MasterGroupListVo item : masterGroupListVos){
            String cateNames = scriptService.getNamesByIds(item.getScriptCateId(), 0);
            item.setScriptCateName(cateNames);
        }
        return masterGroupListVos;
    }

    /**
     * 店主开始组局
     * @param groupId
     * @return
     */
    public boolean startGroup(String groupId){
        Group group = groupService.getById(groupId);
        if(Objects.isNull(group)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"组局不存在");
        }
        String masterId = group.getMasterId();
        group.setGroupType(2);
        try {
            boolean result = groupService.updateById(group);
            if(result){
                Master master = masterService.getById(masterId);
                master.setDmStatus(1);
                master.setTotalDmTimes(master.getTotalDmTimes()+1);
                return masterService.updateById(master);
            }
        } catch (Exception e) {
            log.info("开局失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 店主结束组局
     * @param groupId
     * @return
     */
    public boolean overGroup(String groupId){
        Group group = groupService.getById(groupId);
        if(Objects.isNull(group)){
            throw new ShopException(ErrorCode.PARAMS_GET_ERROR,"组局不存在");
        }
        String masterId = group.getMasterId();
        group.setGroupType(3);
        try {
            boolean result = groupService.updateById(group);
            if(result){
                Master master = masterService.getById(masterId);
                master.setDmStatus(0);
                return masterService.updateById(master);
            }
        } catch (Exception e) {
            log.info("结束组局失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 某个组局里的用户列标
     * @return
     */
    public List<SimpleUserInfoVo> userInGroup(String groupId){
        return this.baseMapper.userInGroup(groupId);
    }


    /**
     * 首页统计
     * @return
     */
    public HomePageStatisticsVo homePageStatistics(){
        HomePageStatisticsVo homePageStatisticsVo = new HomePageStatisticsVo();
        String shopId = userService.getGlobalShopId();
        //今日开始结束时间
        HashMap<String, String> dayStartAndEndTime = HelpUtils.getDayStartAndEndTime(null);
        String todayStartDate = dayStartAndEndTime.get("startDate");
        String todayEndDate = dayStartAndEndTime.get("endDate");
        //昨日开始时间时间
        DateTime yesterday = DateUtil.yesterday();
        String yesterdayStartDate = DateUtil.format(DateUtil.beginOfDay(yesterday),"yyyy-MM-dd HH:mm:ss");
        String yesterdayEndDate = DateUtil.format(DateUtil.endOfDay(yesterday),"yyyy-MM-dd HH:mm:ss");
        //今日开局
        int todayGroupCount = groupService.count(new QueryWrapper<Group>()
                .lambda()
                .eq(Group::getShopId, shopId)
                .ge(Group::getCreatedTime,todayStartDate)
                .le(Group::getCreatedTime,todayEndDate));
        //昨日开局
        int yesterdayGroupCount = groupService.count(new QueryWrapper<Group>()
                .lambda()
                .eq(Group::getShopId, shopId)
                .ge(Group::getCreatedTime,yesterdayStartDate)
                .le(Group::getCreatedTime,yesterdayEndDate));
        HashMap<String, Object> numberTrendValue = HelpUtils.getNumberTrendValue(todayGroupCount, yesterdayGroupCount);
        NumberVo groupVo = new NumberVo();
        groupVo.setTodayNum(todayGroupCount);
        groupVo.setYesterdayNum(yesterdayGroupCount);
        groupVo.setTrendType((Integer) numberTrendValue.get("trendType"));
        groupVo.setTrendValue((String) numberTrendValue.get("trendValue"));
        homePageStatisticsVo.setGroupStat(groupVo);
        //今日营业额
        HashMap<String, Object> orderStatisticsToday = orderDao.orderStatistics(shopId, todayStartDate, todayEndDate);
        double payPriceToday = Double.parseDouble(orderStatisticsToday.get("payPrice").toString());
        double appointPriceToday = Double.parseDouble(orderStatisticsToday.get("appointPrice").toString());
        double totalAmountToday = BigDecimalMathUtil.add(payPriceToday,appointPriceToday);
        //昨日营业额
        HashMap<String, Object> orderStatisticsYesterday = orderDao.orderStatistics(shopId, yesterdayStartDate, yesterdayEndDate);
        double payPriceYesterday = Double.parseDouble(orderStatisticsYesterday.get("payPrice").toString());
        double appointPriceYesterday = Double.parseDouble(orderStatisticsYesterday.get("appointPrice").toString());
        double totalAmountYesterday = BigDecimalMathUtil.add(payPriceYesterday,appointPriceYesterday);
        HashMap<String, Object> orderTrendValue = HelpUtils.getNumberTrendValue(totalAmountToday, totalAmountYesterday);
        DoubleVo orderStat = new DoubleVo();
        orderStat.setTodayNum(totalAmountToday);
        orderStat.setYesterdayNum(totalAmountYesterday);
        orderStat.setTrendType((Integer) orderTrendValue.get("trendType"));
        orderStat.setTrendValue((String) orderTrendValue.get("trendValue"));
        homePageStatisticsVo.setOrderStat(orderStat);
        //总营业额
        HashMap<String, Object> orderStatisticsTotal = orderDao.orderStatistics(shopId, null, null);
        double payPriceTotal = Double.parseDouble(orderStatisticsTotal.get("payPrice").toString());
        double appointPriceTotal = Double.parseDouble(orderStatisticsTotal.get("appointPrice").toString());
        double totalAmountTotal = BigDecimalMathUtil.add(payPriceTotal,appointPriceTotal);
        homePageStatisticsVo.setTotalTurnover(totalAmountTotal);
        //今日用户数
        int todayUserCount = userDao.userStatistics(shopId, todayStartDate, todayEndDate,0);
        //昨日用户数
        int yesterdayUserCount = userDao.userStatistics(shopId, yesterdayStartDate, yesterdayEndDate,0);
        HashMap<String, Object> userTrendValue = HelpUtils.getNumberTrendValue(todayUserCount, yesterdayUserCount);
        NumberVo userStat = new NumberVo();
        userStat.setTodayNum(todayUserCount);
        userStat.setYesterdayNum(yesterdayUserCount);
        userStat.setTrendType((Integer) userTrendValue.get("trendType"));
        userStat.setTrendValue((String) userTrendValue.get("trendValue"));
        homePageStatisticsVo.setUserStat(userStat);
        //今日会员数
        int todayMemberCount = userDao.userStatistics(shopId, todayStartDate, todayEndDate,1);
        //昨日会员数
        int yesterdayMemberCount = userDao.userStatistics(shopId, yesterdayStartDate, yesterdayEndDate,1);
        HashMap<String, Object> memberTrendValue = HelpUtils.getNumberTrendValue(todayMemberCount, yesterdayMemberCount);
        NumberVo memberStat = new NumberVo();
        memberStat.setTodayNum(yesterdayMemberCount);
        memberStat.setYesterdayNum(yesterdayUserCount);
        memberStat.setTrendType((Integer) memberTrendValue.get("trendType"));
        memberStat.setTrendValue((String) memberTrendValue.get("trendValue"));
        homePageStatisticsVo.setMemberStat(memberStat);
        //订单总数
        Integer totalOrder = orderDao.selectCount(new QueryWrapper<Order>()
                .lambda()
                .eq(Order::getShopId, shopId)
                .eq(Order::getHasPay, 1));
        homePageStatisticsVo.setTotalOrderNum(totalOrder);
        return homePageStatisticsVo;
    }

    /**
     * 申请注册小程序后添加店铺
     * @param registerWechat
     * @return
     */
    public String addShopByRegisterWechat(RegisterWechat registerWechat){
        try {
            Shop shop = new Shop();
            String shopName = registerWechat.getCompanyName();
            String phone = registerWechat.getComponentPhone();
            shop.setShopName(shopName);
            shop.setLoginName(phone);
            shop.setMobile(phone);
            String encodePass = PasswordUtils.encode("123456");
            shop.setPassword(encodePass);
            Date expireDate = DateUtil.offset(new Date(), DateField.YEAR, 1);
            shop.setExpireTime(expireDate);
            shop.setCreatedTime(new Date());
            this.save(shop);
            return shop.getShopId();
        } catch (Exception e) {
            log.info("申请注册小程序后添加店铺失败："+e.getMessage());
        }
        return "";
    }

    /**
     * 店铺信息
     * @return
     */
    public ShopDetailVo shopDetail(){
        try {
            String shopId = userService.getGlobalShopId();
            Shop shop = this.getById(shopId);
            return ConvertUtils.sourceToTarget(shop,ShopDetailVo.class);
        } catch (Exception e) {
            log.info("获取店铺信息失败："+e.getMessage());
        }
        return null;
    }

    /**
     * 店铺设置
     * @param params
     * @return
     */
    public boolean saveShopInfo(SaveShopSettingParams params){
        try {
            String shopId = userService.getGlobalShopId();
            Shop shop = ConvertUtils.sourceToTarget(params, Shop.class);
            shop.setShopId(shopId);
            return this.updateById(shop);
        } catch (Exception e) {
            log.info("店铺信息设置失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 店铺修改密码
     * @param params
     * @return
     */
    public boolean changePass(ShopChangePassParams params){
        if(!Objects.equals(params.getPassWord(), params.getConfirmPassWord())){
            throw new ShopException(ErrorCode.ACCOUNT_NOT_EXIST,"2次密码输入不一致");
        }
        String shopId = userService.getGlobalShopId();
        Shop shop = this.getById(shopId);
        boolean checkPwd = PasswordUtils
                .matches(shop.getPassword(), params.getTimestamp(), params.getOldPassWord());
        if(!checkPwd){
            throw new ShopException(ErrorCode.ACCOUNT_NOT_EXIST,"原密码错误");
        }
        try {
            shop.setPassword(params.getPassWord());
            return this.updateById(shop);
        } catch (Exception e) {
            log.info("密码修改失败："+e.getMessage());
        }
        return false;
    }

    /**
     * 热门店铺排行
     * @param offset
     * @return
     */
    public List<TopShopByGroup> topShopByGroup(Integer offset){
        return this.baseMapper.topShopByGroup(offset);
    }
}